# -*- coding:utf-8 -*-
from nameko.standalone.rpc import ClusterRpcProxy
from Common.dbhelper import DBHelper
from Common.models import PvMeta
from Common.settings import config, RTCdata_url, Alertdata_url
# from script.logger import logger
# import json
import schedule
import json
import time
import math
import sys

session_client = None
ws_RTCdata = None
ws_Alertdata = None


def init_db():
    global client
    if not client:
        dbhelper = DBHelper(conf=None)
        session_client = dbhelper.Session()
    return session_client


def optimize_plane_rpc():
    with ClusterRpcProxy(config) as cluster_rpc:
        # hdatas = cluster_rpc.scada_service.get_histrydatas.call_async()
        # hdatas = cluster_rpc.scada_service.hello.call_async("jiang")
        # hdatas = cluster_rpc.modbus_service.send_data.call_async(function_code=6,
        #                                                          starting_address=5,
        #                                                          output_value=0)
        hdatas = cluster_rpc.modbus_service.realtime_commands_db.call_async()
        print("start modbus send!")
        data = hdatas.result()
        print(data)


def optimize_plane_db():
    session_client = init_db()
    pvmetas = session_client.query(PvMeta).all()
    pvmetasArr = []
    for pvmeta in pvmetas:
        pvmetasArr.append(pvmeta.as_dict())


def getRTCdata_send(websocket=ws_RTCdata, points_list=""):
    """
    通过websocket获取实时数据，发送需要获取数据的点列表points_list，以逗号分隔；
    服务器每秒返回一次获取的点的值，顺序与points_list点顺序一致；
    返回值由websocket_wk.data_websocket.on_message()处理。
    """
    #points_list = "Serial4.储能battery@系统工作模式,Serial4.储能battery@电网总功率,Serial4.储能battery@电池Soc"
    lenght = len(points_list)+3
    data_list = "20150001" + "%04d" % lenght + "[9]" + points_list  # "{:0>4d}".format(lenght)
    websocket.send(data_list)


def setRTCdata_send(websocket=ws_RTCdata, point="", value=0):
    """
    通过websocket给设定值，point为要设置的点，value为设定值
    返回值由websocket_wk.data_websocket.on_message()处理。
    """
    set_value = point + "=" + str(value)
    lenght = len(set_value)+3
    set_data = "20150009" + "%04d" % lenght + "[8]" + set_value
    websocket.send(set_data)


"""-----------------------------websocket data:begin------------------------------"""
# #  通过websocket方式可获取实时数据及报警信息
# alert_url = "ws://dr-epic.vicp.io:9998"
#
# def initial():
#     websocket.enableTrace(True)
#     ws_alert = websocket.WebSocketApp(url=alert_url, on_message=on_message,
#                                      on_error=on_error, on_close=on_close)
#     # 获取实时数据、下发定值
#     # self.ws_rtc = websocket.WebSocketApp("ws://192.168.1.10:51684", on_message=self.on_message,
#     #                                  on_error=self.on_error, on_close=self.on_close)
#     ws_alert.on_open = on_open
#     ws_alert.run_forever()
#     return ws_alert
#
# def on_message(ws_alert, message):
#     if message.count("@#$") > 4:  # 获取报警窗口（实时报警信息）
#         try:
#             alert_time, alert_point, alert_name, alert_script, \
#             alert_action, alert_voice, alert_type, alert_value = message.split("@#$")
#         except:
#             return
#         """判断报警点及报警类型，并执行相关操作"""
#         # with ClusterRpcProxy(config) as cluster_rpc:
#         # hdatas = cluster_rpc.ecod_service.grid_control_fun.call_async()
#         print(message)
#     else:  # 获取报警持续状态信息
#         alert_info = (message.split("[")[1]).split("]")[0]
#         alert_info = json.loads(alert_info) if alert_info else message
#         print(alert_info)
#
# def on_error(ws_alert, error):
#     logger.info("Websocket:"+error)
#
# def on_close(ws_alert):
#     logger.info("Websocket closed !!")
#
# def on_open(ws_alert):
#     def run():
#         ws_alert.send("201500110000")  # 心跳报文，超过10s(获取实时值)、20s(获取报警信息)服务器断开链路
#         heartbeat = threading.Timer(5, run)
#         heartbeat.start()
#     heartbeat = threading.Timer(5, run)
#     heartbeat.start()
#
#
"""
通过websocket方式可获取实时数据及报警信息
"""
#
#
# class data_websocket(websocket.WebSocketApp):
#     def __init__(self, url=None, timeinterval=5):
#         self.timeinterval = timeinterval
#         self.heartbeat = None
#         super(data_websocket, self).__init__(url=url,on_open=self.on_open,on_message=self.on_message,
#                                              on_error=self.on_error,on_close=self.on_close)
#
#     def on_message(self, message):
#         if message.count("@#$") > 4:  # 获取报警窗口（实时报警信息）
#             try:
#                 alert_time, alert_point, alert_name, alert_script, \
#                 alert_action, alert_voice, alert_type, alert_value = message.split("@#$")
#             except:
#                 return
#             """判断报警点及报警类型，通过RPC接口执行相关操作"""
#             # with ClusterRpcProxy(config) as cluster_rpc:
#             # hdatas = cluster_rpc.ecod_service.grid_control_fun.call_async()
#             print(message)
#         elif message.startswith("20150002") and message.find("[9]")>0:  # 实时数据返回
#             data = message.split("[9]")[1]
#             """返回的实时数据值（频率每秒一次），通过RPC接口执行相关操作"""
#             print(data)
#         elif message.startswith("20150010") and message.find("[8]") > 0:  # 设定值结果返回，0失败，1成功
#             data = message.split("[8]")[1]
#         else:  # 获取报警持续状态信息
#             alert_info = (message.split("[")[1]).split("]")[0]
#             alert_info = json.loads(alert_info) if alert_info else message
#             print(alert_info)
#
#     def on_error(self, error):
#         logger.info("Websocket:" + error)
#
#     def on_close(self):
#         self.heartbeat.cancel()
#         logger.info("Websocket closed !!")
#
#     def on_open(self):
#         def run():
#             self.send("201500110000")  # 心跳报文，超过10s(获取实时值)、20s(获取报警信息)服务器断开链路
#             self.heartbeat = threading.Timer(self.timeinterval, run)
#             self.heartbeat.start()
#         self.heartbeat = threading.Timer(self.timeinterval, run)
#         self.heartbeat.start()
#         # file = open("cyc.log", "w")
#         # file.write("123\n")
#         # file.close()
#
#
"""-----------------------------websocket data:end------------------------------"""

#schedule.every(30).minutes.do(optimize_plane_db)  #
#schedule.every().minutes.do(optimize_plane_rpc)  #
#schedule.every().day.at("02:30").do(optimize_plane_db)  #
schedule.every(10).seconds.do(optimize_plane_rpc)  #
schedule.every(30).minutes.do(optimize_plane_db)

def start():
    while True:
        schedule.run_pending()
        #time.sleep(10)


if __name__ == '__main__':
    # websocket.enableTrace(True)
    # ws_Alertdata = data_websocket(url=Alertdata_url, timeinterval=5)
    # alert = threading.Thread(target=ws_Alertdata.run_forever)
    # alert.start()
    # ws_RTCdata = data_websocket(url=RTCdata_url, timeinterval=15)
    # rtc = threading.Thread(target=ws_RTCdata.run_forever)
    # rtc.start()
    # time.sleep(10)
    # ws_RTCdata.send("201500010075[9]Serial4.储能battery@系统工作模式,Serial4.储能battery@电网总功率,Serial4.储能battery@电池Soc")

    start()
    # update_schedule()
